﻿using SIG.Model.Store;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace SIG.Service.Store
{
    public partial class ShoppingCart
    {
        private readonly ICartService _cartService;     
        private readonly IOrderService _orderService;
     //  private IMapper _mapper;
        public ShoppingCart(ICartService cartService, IOrderService orderService)
        {            
            _cartService = cartService;
            _orderService = orderService;
            //   _mapper = mapper;
            //ShoppingCartId = "fdsfsd";
        }

   //   MusicStoreEntities storeDB = new MusicStoreEntities();
        public string ShoppingCartId { get; set; }
        public const string CartSessionKey = "CartId";

        public static ShoppingCart GetCart(HttpContextBase context, ICartService cartService, IOrderService orderService)
        {
            var cart = new ShoppingCart(cartService, orderService);
            cart.ShoppingCartId = cart.GetCartId(context);
            return cart;
        }
        // Helper method to simplify shopping cart calls
        public static ShoppingCart GetCart(Controller controller, ICartService cartService, IOrderService orderService)
        {
            return GetCart(controller.HttpContext, cartService, orderService);
        }

        public void AddToCart(Goods goods)
        {
            // Get the matching cart and album instances
            var cartItem = _cartService.SingleOrDefault(ShoppingCartId, goods.Id);             

            if (cartItem == null)
            {
                // Create a new cart item if no cart item exists
                cartItem = new Cart
                {
                    GoodsId = goods.Id,
                    CartId = ShoppingCartId,
                    Count = 1,
                    DateCreated = DateTime.Now
                };
                _cartService.Create(cartItem);
            }
            else
            {
                // If the item does exist in the cart, 
                // then add one to the quantity
                cartItem.Count++;
                _cartService.Update(cartItem);
            }
            // Save changes
            // storeDB.SaveChanges();
        }
        public int RemoveFromCart(int id)
        {
            // Get the cart
            var cartItem = _cartService.Single(ShoppingCartId,id);

            int itemCount = 0;

            if (cartItem != null)
            {
                if (cartItem.Count > 1)
                {
                    cartItem.Count--;
                    itemCount = cartItem.Count;
                    _cartService.Update(cartItem);
                }
                else
                {
                    _cartService.Delete(cartItem);
                }
                // Save changes
               // storeDB.SaveChanges();
            }
            return itemCount;
        }
        public void EmptyCart()
        {
            _cartService.EmptyCart(ShoppingCartId);
            //var cartItems = _cartService.FindBy(cart => cart.CartId == ShoppingCartId);
            //foreach (var cartItem in cartItems)
            //{
            //    _cartService.Delete(cartItem);
            //}         
        }
        public List<Cart> GetCartItems()
        {
            return _cartService.FindBy(cart => cart.CartId == ShoppingCartId).ToList();
        }
        public int GetCount()
        {
            // Get the count of each item in the cart and sum them up
            int? count = _cartService.GetAll().Where(cart => cart.CartId == ShoppingCartId).Select(cart => (int?)cart.Count).Sum();

            //(from cartItems in storeDB.Carts
            //              where cartItems.CartId == ShoppingCartId
            //              select (int?)cartItems.Count).Sum();
            // Return 0 if all entries are null
            return count ?? 0;
        }
        public decimal GetTotal()
        {
            // Multiply album price by count of that album to get 
            // the current price for each of those albums in the cart
            // sum all album price totals to get the cart total
            decimal? total = _cartService.GetAll().Where(cart => cart.CartId == ShoppingCartId).Select(cart => (int?)cart.Count * cart.Goods.Price).Sum();
                //(from cartItems in storeDB.Carts
                //              where cartItems.CartId == ShoppingCartId
                //              select (int?)cartItems.Count *
                //              cartItems.Album.Price).Sum();

            return total ?? decimal.Zero;
        }
        public int CreateOrder(Order order)
        {
            decimal orderTotal = 0;
            var cartItems = GetCartItems();
            // Iterate over the items in the cart, 
            // adding the order details for each
            foreach (var item in cartItems)
            {
                var orderDetail = new OrderDetail
                {
                    GoodsId = item.GoodsId,
                    OrderId = order.Id,
                    UnitPrice = item.Goods.Price,
                    Quantity = item.Count
                };
                // Set the order total of the shopping cart
                orderTotal += (item.Count * item.Goods.Price);

                order.OrderDetails.Add(orderDetail);

               // _orderDetailService.Create(orderDetail);

            }
            // Set the order's total to the orderTotal count
            order.Total = orderTotal;
            // Save the order
            _orderService.Create(order);
            // Empty the shopping cart
            EmptyCart();
            // Return the OrderId as the confirmation number
            return order.Id;
        }
        // We're using HttpContextBase to allow access to cookies.
        public string GetCartId(HttpContextBase context)
        {
            if (context.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
                {
                    context.Session[CartSessionKey] = context.User.Identity.Name;
                }
                else
                {
                    // Generate a new random GUID using System.Guid class
                    Guid tempCartId = Guid.NewGuid();
                    // Send tempCartId back to client as a cookie
                    context.Session[CartSessionKey] = tempCartId.ToString();
                }
            }
            return context.Session[CartSessionKey].ToString();
        }
        // When a user has logged in, migrate their shopping cart to
        // be associated with their username
        public void MigrateCart(string userName)
        {
            _cartService.MigrateCart(ShoppingCartId, userName);
         
        }
    }
}
